<?php

namespace api\components;

use common\helpers\commonApi;
use common\helpers\JwtApi;
use common\models\User;
use yii\web\Controller;
use Yii;

/**
 * Default controller for the `v1` module
 */
class BaseController extends Controller
{
    public static $userid = '';
    public static $jwtId = 'tea_activities';
    public static $notLogin = [
        'home/carousel',
        'home/system',
        'home/nav',
        'home/recent',
        'home/recommend',
        'equity/classify',
        'equity/boutique',
        'equity/list',
        'equity/details',
        'activity/common',
        'activity/list',
        'activity/get-like',
        'activity/details',
        'activity/get-evaluate',
        'login/login',
        'goods/classify',
        'goods/list',
        'goods/details',
        'goods/get-comment',
        'vip/list',
    ];
    public function actions()
    {
        $path = Yii::$app->request->pathInfo;
        $jwt = new JwtApi(self::$jwtId);
        $token = $jwt->getRequestToken();
        $id = $jwt->getUserId($token);
        header('Content-Type:application/json; charset=utf-8');
        $notLogin = self::$notLogin;
        if (in_array($path,$notLogin)==false){//必须登录
            if (!$id){
                $da = commonApi::message('请授权登录',false,'',101);
                exit(json_encode($da));
            }
        }
        if ($id){
            $exists = User::find()->where(['id'=>$id,'status'=>1])->exists();
            if (!$exists){
                $da = commonApi::message('请授权登录',false,'',101);
                exit(json_encode($da));
            }
            self::$userid = $id;
        }
        return true;
    }
    /**
     * 返回JSON结果
     * @param bool $isreturn 是否返回json  false时为在beforeAction中返回
     * @return B5Response
     */
    protected function returnJson($isreturn=true){
        $callback=\Yii::$app->request->get('b5appcallback','');
        if(!$callback){
            $callback=\Yii::$app->request->get('callback','');
        }
        return new B5Response($callback,$isreturn);
    }

    /**
     * 获取model的错误信息
     * @param $model
     * @return string
     */
    protected function getFerror($model){
        $error='';
        if($model && $model->firstErrors){
            foreach($model->firstErrors as $val){
                $error=$val;break;
            }
        }
        return empty($error)?'发生错误了':$error;
    }

    public function BUG($data)
    {
        $data = is_array($data) ? var_export($data, true) : $data;
        file_put_contents("bu.txt", date('Y/m/d H:i:s', time()) . " \t输出结果:" . $data . "\r\n\r\n", FILE_APPEND);
        return true;
    }
}
